package com.xiangban.yanglaodajie_platform.rabbit;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiangban.yanglaodajie_platform.dao.GoodsMapper;
import com.xiangban.yanglaodajie_platform.dao.OrdersMapper;
import com.xiangban.yanglaodajie_platform.entity.Orders;
import com.xiangban.yanglaodajie_platform.entity.dto.OrdersDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RabbitListener(queues = "order.cancel")
public class CancelOrderReceiver {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    private static Logger LOGGER = LoggerFactory.getLogger(CancelOrderReceiver.class);

    @RabbitHandler
    public void handle(String orderId){
        Orders orders = new Orders();
        orders.setOrderNumber(orderId);
        OrdersDto orderInfo = ordersMapper.orderInfoByOderNo(orders);
        if (orderInfo!=null){
            if ("-1".equals(orderInfo.getOrderStatus())){
                HashMap<String, Object> parameter = new HashMap<>();
                parameter.put("order_status","3");
                parameter.put("order_number",orderId);
                ordersMapper.updOrderStatus(parameter);
                LOGGER.info(orderId+"：订单已经取消");
                //库存返回
                String goodSku = orderInfo.getGoodSku();
                JSONArray jsonArray = JSON.parseArray(goodSku);
                for (Object o : jsonArray) {
                    Map<String,Object> map = JSONObject.parseObject(JSONObject.toJSONString(o), Map.class);
                    goodsMapper.updateInventory(map);
                }
            }

        }

    }
}
